package cn.jetpiece.cloud.joss.api.basic;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.joss.api.basic.model.params.ObjectPathInfo;
import cn.jetpiece.cloud.joss.api.basic.model.params.ObjectPathParam;
import cn.jetpiece.cloud.joss.api.basic.model.params.ObjectPrefixInfo;
import cn.jetpiece.cloud.joss.api.basic.model.params.ObjectPrefixParam;
import cn.jetpiece.cloud.joss.api.basic.model.result.ObjectPathResult;
import cn.jetpiece.cloud.joss.api.basic.utils.JossUploadUtils;
import cn.jetpiece.cloud.joss.api.config.properties.JossClientProperties;
import cn.jetpiece.cloud.model.response.Result;
import cn.jetpiece.cloud.resource.annotation.annotation.ApiResource;
import cn.jetpiece.cloud.resource.annotation.annotation.ScanResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 基础的上传接口
 *
 * @author XuJZ
 */
@Api(tags = "基础的上传接口")
@ApiResource(name = "基础的上传接口")
public interface BasicUploadApi {

    String API = "/${jetpiece.joss-client.upload-api-path:" + JossClientProperties.UPLOAD_API_PATH + "}";

    /**
     * 获取访问路径前缀
     */
    @ApiOperation(value = "获取访问路径前缀")
    @ScanResource(name = "获取访问路径前缀", path = API + "/base-url-prefix", method = RequestMethod.GET)
    default String getBaseUrlPrefix() {
        return JossClientProperties.getInstance().getBaseUrlPrefix();
    }

    /**
     * 删除对象
     */
    @ApiOperation(value = "删除对象")
    @ScanResource(name = "删除对象", path = API + "/delete-object", method = RequestMethod.DELETE)
    default Result<String> deleteObject(@RequestParam("url") String url) {
        String path = url.replaceFirst(getBaseUrlPrefix(), "");
        return JossUploadUtils.getJossFeignToken().deleteObject(path);
    }

    /**
     * 获取对象地址
     */
    @ApiOperation(value = "获取对象地址")
    @ScanResource(name = "获取对象地址", path = API + "/object-paths", method = RequestMethod.POST)
    default Result<ObjectPathResult> objectPaths(@Valid @RequestBody ObjectPathParam param) {
        JossClientProperties properties = JossClientProperties.getInstance();
        /* 文件路径默认值 */
        String defaultFilePath = JossUploadUtils.formatPath(param.getFilePath(), properties.getDefaultFilePath());
        /* 是否重命名默认值 */
        boolean defaultRename = param.getRename() != null ? param.getRename() : false;
        for (ObjectPathInfo objectPathInfo : param.getInfos()) {
            List<String> elements = new ArrayList<>();
            /* 模块路径 */
            String filePath = JossUploadUtils.formatPath(objectPathInfo.getFilePath(), defaultFilePath);
            /* 日期路径 */
            String datePath = null;
            if (StrUtil.isNotBlank(properties.getDateFormat())) {
                datePath = DateUtil.format(new Date(), properties.getDateFormat());
            }
            String objectName;
            /* 是否重命名 */
            boolean rename = objectPathInfo.getRename() != null ? objectPathInfo.getRename() : defaultRename;
            if (rename) {
                String uuid = UUID.randomUUID().toString();
                JossUploadUtils.formatPathJoin(elements, properties.getDefaultBucketName(), properties.getDefaultPathPrefix(), filePath, datePath, uuid);
                int lastPointIndex = objectPathInfo.getFileName().lastIndexOf(".");
                if (lastPointIndex != -1) {
                    objectName = StrUtil.join("/", elements) + objectPathInfo.getFileName().substring(lastPointIndex);
                } else {
                    objectName = StrUtil.join("/", elements);
                }
            } else {
                if (StrUtil.isBlank(objectPathInfo.getFileName())) {
                    return Result.error("文件名不能为空");
                }
                JossUploadUtils.formatPathJoin(elements, properties.getDefaultBucketName(), properties.getDefaultPathPrefix(), filePath, datePath, objectPathInfo.getFileName());
                objectName = StrUtil.join("/", elements);
            }
            objectPathInfo.setObjectName(objectName.substring(objectName.indexOf("/") + 1));
            objectPathInfo.setUrl(JossClientProperties.getInstance().getBaseUrlPrefix() + objectName);
            /* 生成Token */
            objectPathInfo.setJossToken(JossUploadUtils.getJossToken(param.getPreSign(), param.getPreExpires(), objectName));
        }
        ObjectPathResult objectPathResult = new ObjectPathResult();
        objectPathResult.setInfos(param.getInfos());
        return Result.OK(objectPathResult);
    }

    /**
     * 获取对象地址前缀
     */
    @ApiOperation(value = "获取对象地址前缀")
    @ScanResource(name = "获取对象地址前缀", path = API + "/object-prefix", method = RequestMethod.POST)
    default Result<ObjectPrefixInfo> objectPrefix(@Valid @RequestBody ObjectPrefixParam param) {
        JossClientProperties properties = JossClientProperties.getInstance();
        String baseUrlPrefix = JossClientProperties.getInstance().getBaseUrlPrefix();
        List<String> elements = new ArrayList<>();
        String filePath = JossUploadUtils.formatPath(param.getFilePath(), properties.getDefaultFilePath());
        JossUploadUtils.formatPathJoin(elements, properties.getDefaultBucketName(), properties.getDefaultPathPrefix(), filePath);
        String path = StrUtil.join("/", elements);
        ObjectPrefixInfo result = new ObjectPrefixInfo();
        result.setFilePath(param.getFilePath());
        result.setPath(path.substring(path.indexOf("/") + 1));
        result.setUrl(baseUrlPrefix + path);
        result.setJossToken(JossUploadUtils.getJossToken(param.getPreSign(), param.getPreExpires(), path));
        return Result.OK(result);
    }
}
